package com.woniu.utils;

import com.woniu.entity.LoginCount;
import com.woniu.entity.User1;
import com.woniu.pojo.User;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class SessionNumber implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {


        String userName=httpSessionBindingEvent.getName();
        if(userName.equals("user")){

                LoginCount loginCount=LoginCount.getInstance();
                 User1 user = (User1) httpSessionBindingEvent.getValue();
            HttpSession session = loginCount.getSessionByUserName(user.getUname());
            if(session!=null){
                session.invalidate();
            }
                Integer count=0;
                Integer count1 = (Integer) httpSessionBindingEvent.getSession().getServletContext().getAttribute("online");
                if(count1!=null){

                    count=count1;

                };
                count++;
                httpSessionBindingEvent.getSession().getServletContext().setAttribute("online",count);



            loginCount.saveUserAndSession(user.getUname(), httpSessionBindingEvent.getSession());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        String userName=httpSessionBindingEvent.getName();
        if(userName.equals("user")){


                Integer count = (Integer) httpSessionBindingEvent.getSession().getServletContext().getAttribute("online");
                if(count!=null){

                    count--;

                };

                httpSessionBindingEvent.getSession().getServletContext().setAttribute("online",count);

            }


    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}
